﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using MySql.Data.MySqlClient;

namespace student_systemApp
{
    public partial class AddStudentForm : Form
    {
        public AddStudentForm()
        {
            InitializeComponent();
        }

        private void AddStudentForm_Load(object sender, EventArgs e)
        {
            //初始化班级加载列表
            initClass();
            //性别默认男
            radioButton_man.Checked = true;
        }

        private void initClass()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["UserManagementConnectionString"].ConnectionString;
            string sql = "SELECT class_id,class_name,grade_name from" +
                " class c " +
                "inner join" +
                " grade g on c.grade_id = g.grade_id" +
                " order by g.grade_id ASC";

            using (var connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    MySqlCommand command = new MySqlCommand(sql, connection);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(command);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);

                    DataRow row = dt.NewRow();
                    row["class_name"] = "请选择";
                    row["class_id"] = 0;
                    dt.Rows.InsertAt(row, 0);

                    foreach (DataRow dr in dt.Rows)
                    {
                        if ((int)dr["class_id"] != 0) // 跳过默认项
                        {
                            string originalClassName = (string)dr["class_name"];
                            string originalGradeName = (string)dr["grade_name"];
                            dr["class_name"] = originalClassName + "----" + originalGradeName;
                        }
                    }
                    //绑定数据
                    comboBox_class.DataSource = dt;
                    comboBox_class.DisplayMember = "class_name";
                    comboBox_class.ValueMember = "class_id";

                    //默认选择0
                    comboBox_class.SelectedIndex = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("查找失败" + ex.Message, "提示");
                }
                connection.Close();
            }
        }

        private void button_submit_Click(object sender, EventArgs e)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["UserManagementConnectionString"].ConnectionString;

            // 获取页面上的数据
            string sqlInsert = "INSERT INTO student (student_name, class_id, sex, phone_number, grade_id) VALUES (@studentName, @classId, @sex, @phoneNumber, @gradeId)";
            string sqlSelect = "SELECT grade_id FROM class WHERE class_id = @classId";

            using (var connection = new MySqlConnection(connectionString))
            {
                try
                {
                    string studentName = textBox_studentName.Text;
                    int classId = (int)comboBox_class.SelectedValue;
                    string sex = radioButton_man.Checked ? "M" : "F";
                    string phoneNumber = textBox_phoneNumber.Text;

                    if (studentName == "")
                    {
                        MessageBox.Show("请输入学生姓名", "提示");
                        return;
                    }
                    if (classId == 0)
                    {
                        MessageBox.Show("请选择班级", "提示");
                        return;
                    }
                    if (phoneNumber == "")
                    {
                        MessageBox.Show("请输入正确手机号", "提示");
                        return;
                    }

                    // 创建连接
                    connection.Open();

                    // 先查询班级对应的年级ID
                    using (var selectCommand = new MySqlCommand(sqlSelect, connection))
                    {
                        selectCommand.Parameters.AddWithValue("@classId", classId);
                        int? gradeId = selectCommand.ExecuteScalar() as int?;

                        // 准备插入命令
                        using (var insertCommand = new MySqlCommand(sqlInsert, connection))
                        {
                            insertCommand.Parameters.AddWithValue("@studentName", studentName);
                            insertCommand.Parameters.AddWithValue("@classId", classId);
                            insertCommand.Parameters.AddWithValue("@sex", sex);
                            insertCommand.Parameters.AddWithValue("@phoneNumber", phoneNumber);
                            insertCommand.Parameters.AddWithValue("@gradeId", gradeId.Value);

                            int result = insertCommand.ExecuteNonQuery();
                            if (result > 0)
                            {
                                MessageBox.Show("添加成功", "提示");
                                //清空表格内容
                                textBox_studentName.Clear();
                                textBox_phoneNumber.Clear();
                                //性别默认男
                                radioButton_man.Checked = true;
                                comboBox_class.SelectedIndex = 0;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("添加失败: " + ex.Message, "提示");
                }
            }
        }

        private void button_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //单例化
        //private static AddStudentForm addStudentForm = null;

        //public static AddStudentForm Instance
        //{
        //    get
        //    {
        //        if (addStudentForm == null)
        //        {
        //            addStudentForm = new AddStudentForm();
        //        }
        //        return addStudentForm;
        //    }
        //}
    }
}
